package www.ym.com.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;
import www.ym.com.entity.Address;
import www.ym.com.service.AddressService;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 新增收货地址
     *
     * @return
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody Address address) {
        List<Address> list = addressService.list();
        if (list.size() == 5) {
            log.info("列表总数" + list.size());
            throw new CustomException("收货地址最多只能增加5条");
        }
        if (list.size() == 0) {
            //第一条地址设置为默认地址
            address.setIsDefault(0);
            addressService.save(address);
        } else {
            address.setIsDefault(1);
            addressService.save(address);
        }
        return R.success("", "添加成功");
    }

    /**
     * 修改默认收货地址
     *
     * @return
     */
    @PutMapping("/isDefault")
    public R<String> change(@RequestBody Address address) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        //默认地址修改为否
        wrapper.eq(Address::getIsDefault, 0);
        Address one = addressService.getOne(wrapper);
        one.setIsDefault(1);
        addressService.updateById(one);

        Address byId = addressService.getById(address.getId());
        byId.setIsDefault(0);
        addressService.updateById(byId);
        return R.success("", "修改成功");
    }

    /**
     * 修改地址信息
     *
     * @param address
     * @return
     */
    @PutMapping("/chagneInfo")
    public R<String> changeInfo(@RequestBody Address address) {
        addressService.updateById(address);
        return R.success("", "修改成功");
    }

    /**
     * 删除地址信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/del")
    public R<String> del(Long id) {
        addressService.removeById(id);
        return R.success("", "删除成功");
    }

    /**
     * 地址列表
     *
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<Address>> list(Long userId) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,userId).orderByAsc(Address::getIsDefault).orderByDesc(Address::getUpdateTime);
        List<Address> list = addressService.list(wrapper);
        return R.success(list, "处理成功");
    }


}
